package com.cskaoyan._04tx.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author Macro_Ray
 * @since 2024/4/18 下午10:42
 */
public class JdbcUtils {
    private static String driver;

    private static String url;

    private static String username;

    private static String password;

    static {
        // 读取配置文件
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("02-JavaEE/jdbc.properties"));
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 提供一个获取连接的方式
    public static Connection gerConnection() throws ClassNotFoundException, SQLException {
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, username, password);
        return conn;
    }

    // 关闭连接
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (conn != null) {
                conn.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
        }
    }

}
